<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜单名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入菜单名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜单图标" prop="icon">
        <el-input
          v-model="queryParams.icon"
          placeholder="请输入菜单图标"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="跳转页面" prop="name">
        <el-input
          v-model="queryParams.page"
          placeholder="请输入跳转页面"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜单颜色" prop="color">
        <el-input
          v-model="queryParams.color"
          placeholder="请输入菜单颜色"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜单分类">
        <el-select v-model="queryParams.category" placeholder="请选择菜单分类" clearable>
          <el-option
            v-for="item in wxMenuCategoryList"
            :key="item.value"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序序号" prop="sortOrder">
        <el-input
          v-model="queryParams.sortOrder"
          placeholder="请输入排序序号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:menu:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:menu:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:menu:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:menu:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="menuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="${comment}" align="center" prop="id"/>-->
      <el-table-column label="菜单名" align="center" prop="name"/>
      <el-table-column label="菜单图标" align="center" prop="icon">
        <template slot-scope="scope">
          <img v-if="scope.row.icon !== '' " style="width: 4vh;height: 4vh" :src="scope.row.icon" alt="">
        </template>
      </el-table-column>
      <el-table-column label="跳转页面" align="center" prop="page"/>
      <el-table-column label="菜单颜色" align="center" prop="color"/>
      <el-table-column label="菜单分类" align="center" prop="category">
        <template slot-scope="scope">
          {{ getDictValue(scope.row.category, wxMenuCategoryList) }}
        </template>
      </el-table-column>
      <el-table-column label="排序序号" align="center" prop="sortOrder"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:menu:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:menu:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜单名" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜单名"/>
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <el-upload
            :class="{ hide: hideUpload }"
            :auto-upload="false"
            :http-request="httpRequest"
            action="#"
            :limit="1"
            :file-list="fileList"
            :on-exceed="uploadOverrun"
            :on-success="handleGalleryUrl"
            :on-remove="handleRemove"
            :on-change="uploadChange"
            multiple
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card"
          >
            <i class="el-icon-plus"/>
          </el-upload>
        </el-form-item>

        <el-form-item label="跳转页面" prop="page">
          <el-input v-model="form.page" placeholder="请输入跳转页面"/>
        </el-form-item>

        <el-form-item label="菜单颜色" prop="color">
          <el-color-picker
            v-model="form.color"
            show-alpha
            >
          </el-color-picker>
        </el-form-item>
        <el-form-item label="选择菜单分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择">
            <el-option
              v-for="item in wxMenuCategoryList"
              :key="item.name"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序序号" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" placeholder="请输入排序序号" :min="0"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listMenu, getMenu, delMenu, addMenu, updateMenu, uploadMenuIcon,listDetailMenu} from "@/api/system/wxmenusort";
import {listCategories} from "@/api/system/wxmenucategory"
import wxmenucategory from "@/views/system/wxmenucategory/index.vue";

export default {
  name: "Menu",
  computed: {
    wxmenucategory() {
      return wxmenucategory
    },
    hideUpload(){
      return this.fileList.length >=1
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      menuList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        icon: null,
        page:null,
        color: null,
        category: null,
        sortOrder: null,
        isDeleted: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "菜单名不能为空", trigger: "blur"}
        ],
      },
      wxMenuCategoryList: [],
      fileList: [],
    };
  },
  created() {
    this.getList();
    this.getWxMenuCategoryList()
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listDetailMenu(this.queryParams).then(response => {
        this.menuList = response.rows;
        this.total = response.total;
        this.loading = false;

        // 按年龄分类
        let arr = this.menuList.reduce(function (result, item) {
          let key = item.category; // 选取要分类的字段（这里为年龄）

          if (!result[key]) {
            result[key] = []; // 如果该分类不存在则创建空数组
          }

          result[key].push(item); // 添加到相应分类中

          return result;
        }, {});

        console.log(arr)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.fileList = []
      this.form = {
        id: null,
        name: null,
        icon: null,
        page:null,
        color: null,
        category: null,
        sortOrder: null,
        isDeleted: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMenu(id).then(response => {
        this.form = response.data;
        this.form.category = parseInt(response.data.category)
        this.open = true;
        this.fileList = []
        if(this.form.icon){
          this.fileList.push({url: this.form.icon})
        }

        this.title = "修改【请填写功能名称】";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(this.fileList.length ==0){
        this.form.icon = ""
      }
      if(this.fileList.length > 0 && this.fileList[0].raw){
        this.$refs["form"].validate(valid => {
          if (valid) {
            let formData = new FormData();
            formData.append('file', this.fileList[0].raw);
            uploadMenuIcon(formData).then(res => {
              if (res.code == 200) {
                this.form.icon = res.url
                if (this.form.id != null) {
                  updateMenu(this.form).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  });
                } else {
                  addMenu(this.form).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  });
                }
              }
            })
          }
        });
      }else{
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateMenu(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addMenu(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function () {
        return delMenu(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/menu/export', {
        ...this.queryParams
      }, `menu_${new Date().getTime()}.xlsx`)
    },

    async getWxMenuCategoryList() {
      let res = await listCategories()
      this.wxMenuCategoryList = res.rows
    },


    //根据传入的菜单id，获取菜单分类名字
    getDictValue(value, columns) {
      if (columns.length > 0) {
        let info = columns.filter(item => {
          return item.id == value
        })
        return info[0] ? info[0].name : ''
      }
    },

    httpRequest(data) {
      let formData = new FormData();
      formData.append('file', data.file);
      uploadMenuIcon(formData).then(res => {
        if (res.code == 200) {
          this.form.icon = res.url
        }
      })
    },

    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          console.log(reader.result)
        };
      }
    },


    uploadOverrun: function () {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    handleGalleryUrl(response, file, fileList) {
      console.log(response, "res")
      console.log(file, "file")
      console.log(fileList, "fileList")
      if (response.errno === 0) {
        this.goods.gallery.push(response.data.url)
      }
    },
    handleRemove: function (file, fileList) {
      this.fileList = fileList
      // for (var i = 0; i < this.goods.gallery.length; i++) {
      //   // 这里存在两种情况
      //   // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
      //   //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
      //   // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
      //   var url
      //   if (file.response === undefined) {
      //     url = file.url
      //   } else {
      //     url = file.response.data.url
      //   }
      // }
    },


    //文件上传改变的
    uploadChange(file, fileList) {
      this.fileList = fileList
      this.hideUpload = fileList.length >= 1;
      // this.fileList.push(e.raw.File)
      // console.log(this.fileList)
      // console.log(e)
    }


  }
};
</script>

<style>
.upload-img {
  width: 15vh;
  height: 15vh;
}
.hide .el-upload--picture-card {
  display: none;
}

::v-deep .hide .el-upload--picture-card {
  display: none;
}
</style>
